package com.cloud.controller;

import com.cloud.entity.Admin;
import com.cloud.entity.Employee;
import com.cloud.entity.PageInfo;
import com.cloud.service.EmpService;
import com.cloud.utils.GlobalConstant;
import com.cloud.utils.Md5Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author .
 * created in 2020/1/11 7:53
 */

@RestController
@RequestMapping(value = "/emp")
public class EmpController {

    private Logger logger = LoggerFactory.getLogger(EmpController.class);

    private final EmpService empServiceImpl;

    public EmpController(EmpService empServiceImpl) {
        this.empServiceImpl = empServiceImpl;
    }

    @PostMapping(value = "/login")
    public int login(HttpServletRequest request, @RequestParam("name") String name,
                     @RequestParam("password") String password) {
        HttpSession session = request.getSession();
        Employee employee = new Employee();
        employee.setName(name);
        employee.setLock(1);
        Employee emp = empServiceImpl.findEmpByCondition(employee);
        if (emp != null && emp.getPassword().equals(Md5Tools.numberMd5(password))) {
            session.setAttribute("emp", emp);
            logger.info("【{}】登录成功，正在进行跳转······", emp.getName());
            return GlobalConstant.SUCCESS;
        }
        return GlobalConstant.ERROR;
    }

    @PostMapping(value = "/addEmp")
    public int addEmp(Employee employee, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        employee.setCreater(admin.getName());
        employee.setUpdater(admin.getName());
        return empServiceImpl.addEmp(employee);
    }

    @PostMapping(value = "/delEmp/{id}")
    public int delEmp(@PathVariable("id") String id) {
        return empServiceImpl.delEmp(id);
    }

    @PostMapping(value = "/updateEmp")
    public int updateEmp(Employee employee, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        employee.setCreater(admin.getName());
        employee.setUpdater(admin.getName());
        return empServiceImpl.updateEmp(employee);
    }

    @GetMapping(value = "/findAll")
    public PageInfo<Employee> findAll(PageInfo<Employee> info,
                                      @RequestParam(value = "name", defaultValue = "") String name) {
        return empServiceImpl.findAll(info, name);
    }

    @GetMapping(value = "/findById/{id}")
    public Employee findById(@PathVariable("id") int id) {
        return empServiceImpl.findEmpByCondition(new Employee(id));
    }

    @GetMapping(value = "/findByName")
    public Employee findByName(Employee employee) {
        return empServiceImpl.findEmpByCondition(employee);
    }

}
